<?php
namespace addons\paotui\service;

use addons\paotui\library\Map;
use addons\paotui\service\Config as PaotuiConfig;
use app\admin\model\paotui\Brokeragescale;
use app\admin\model\paotui\Distanceprice;
use app\admin\model\paotui\ExtraPrice;
use app\admin\model\paotui\Generalprice;
use app\admin\model\paotui\PostDispatch;
use app\admin\model\paotui\PostOrder;
use app\admin\model\paotui\PostSocket;
use app\admin\model\paotui\UserLevel;
use app\admin\model\paotui\WeightPrice;
use think\Db; 
use app\admin\model\shopro\commission\Order as OrderModel;
use app\admin\model\shopro\commission\Reward as RewardModel;
use app\admin\model\shopro\commission\Log as LogModel;

class Post{
    public $error;
    public static $post_order_type = ['1'=>'支付','2'=>'抢单成功','3'=>'取件',"4"=>'送达'];
    public static $post_order_type2 = ['1'=>'支付','2'=>'抢单成功','3'=>'取件',"4"=>'寄出'];

    public function addPost($data){
        $postModel = new \app\admin\model\paotui\Post();
        Db::startTrans();
        if($postModel->allowField(true)->save($data)){
            $userAddressModel = new UserAddress();
            $userAddressModel->refreshUpdateTime([$data['from_address_id'],$data['to_address_id']],$data['user_id']);
            Db::commit();
            return $postModel;
        }else{
            Db::rollback();
            return false;
        }
    }
    public function savePost($data){
        Db::startTrans();
        if($data->allowField(true)->save()){
            $userAddressModel = new UserAddress();
            $userAddressModel->refreshUpdateTime([$data['from_address_id'],$data['to_address_id']],$data['user_id']);
            Db::commit();
            return $data;
        }else{
            Db::rollback();
            return false;
        }
    }

    /**
     * 获取保价金额
     */
    public function getBPrice($price){
        $bpriceScale = PaotuiConfig::get('bprice_scale');
        $b_price = empty($bpriceScale)?0:bcmul($price,bcdiv($bpriceScale,100,2),2);
        return $b_price;
    }


    /**
     * 获取我的快递列表
     * @return array
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getPostList($status,$where,$page,$limit,$field='*',$sort='status asc,id desc'){
        
        
        
        $total = self::getStatusModel($status)->where($where)->count();

        if($page){
            $data = collection(self::getStatusModel($status)->where($where)->page($page,$limit)->field($field)->order($sort)->select())->toArray();
        }else{
            $data = collection(self::getStatusModel($status)->where($where)->field($field)->order($sort)->select())->toArray();
        }

        foreach ($data as &$v){
            if($v['appoints_day']){
                $today = date("m-d");
                if($today == $v['appoints_day']){
                    $v['appoints_day'] = "今天";
                }

                $tomorrow = date("m-d",strtotime("+1 day",time()));
                if($tomorrow == $v['appoints_day']){
                    $v['appoints_day'] = "明天";
                }
            }
        }

        return array('data'=>$data,'total'=>$total);
    }

    private function getStatusModel($status){
        $model = new \app\admin\model\paotui\Post();

        switch ($status){
            case "1":   //全部
                $model = $model::where(['is_delete'=>0]);
                break;
            case "2":   //进行中
                $model = $model::where(["status"=>['in','2,3,4'],'is_delete'=>0]);
                break;
            case "3":   //已完成
                $model = $model::where(["status"=>5,'is_delete'=>0]);
                break;
            case "4":   //未支付
                $model = $model::where(["pay_status"=>0,'is_delete'=>0]);//"status"=>1,
                break;
            case "5":   //已取消
                $model = $model::where(["status"=>-1,'is_delete'=>0]);
                break;
            default:     //无条件
                $model = $model::where(["status"=>0,'is_delete'=>0]);
                break;
        }

        return $model;

    }

    /**
     * 获取详细的订单金额
     * 返回配送距离、基础配送费、超距费、超重费
     * @return float|int|mixed
     */
    public function getPostDetailPrice($from_address_id,$to_address_id,$user_id,$type=1,$weight=5,$isAddFromPay=0,$pstype=0){
		//pstype 20240830 masks 商城配送类型 11为商超外卖，以后再加再说
        #判断收发件地址是否正确 start#

        if($from_address_id == $to_address_id){
            $this->error = "请选择正确的收发件地址";
            return false;
        }

        $userAddress = new \addons\paotui\service\UserAddress();
        
		if($isAddFromPay){
			$fromAddress = $userAddress->getAddressInfo($from_address_id,0);
		}else{
			$fromAddress = $userAddress->getAddressInfo($from_address_id,$user_id);
		}
        if(empty($fromAddress)){
            $this->error = "请选择正确的发件地址";
            return false;
        }

        $toAddress = $userAddress->getAddressInfo($to_address_id,$user_id);
        if(empty($toAddress)){
            $this->error = "请选择正确的收件地址";
            return false;
        }
        #判断收发件地址是否正确 end#

        #获取基础价格 begin
        $generalpriceModel = new Generalprice();
		if($pstype){
			$configInfo = $generalpriceModel->where(['type'=>$pstype])->find();
		}else{
			$configInfo = $generalpriceModel->where(['type'=>$type])->find();
		}
        
        $general_price = empty($configInfo)?0:$configInfo['price'];
        #获取基础价格 end


        $over_distance = 0;
        $over_distance_price = 0;

        #===获取收发件经纬度之间的距离 km start#
        $map = new Map();
        $distance = $map->getCycleDistance($fromAddress['lng'].",".$fromAddress['lat'],$toAddress['lng'].",".$toAddress['lat']);

        #======获取超出里程和超出里程金额 start#
        $distancePriceModel = new Distanceprice();
        $distancePrice = $distancePriceModel->where(['type'=>$type,'min'=>['elt',$distance]])->select();

        if(!empty($distancePrice)){
            foreach($distancePrice as $k=>$v){
                //计算当前里程内价格
                $_distance = $distance<$v['max']?($distance-$v['min']):($v['max']-$v['min']);
                $over_distance = bcadd($over_distance,$_distance,2);

                $over_distance_price = bcadd($over_distance_price,ceil(bcdiv($_distance,$v['step'],1))*$v['price'],2);
            }
        }
        #======获取超出里程和超出里程金额 end#

        #===获取收发件经纬度之间的距离 km end#

        #获取超出重量和超出重量金额 start#
        $weightPriceModel = new WeightPrice();
        $weightPrice = $weightPriceModel->where(['type'=>$type,'min'=>['elt',$weight]])->select();

        $over_weight = 0;
        $over_weight_price = 0;

        if(!empty($weightPrice)){
            foreach($weightPrice as $k=>$v){
                //计算当前重量内价格
                $_over_weight = $weight<$v['max']?($weight-$v['min']):($v['max']-$v['min']);
                $over_weight = bcadd($over_weight,$_over_weight,2);

                $over_weight_price = bcadd($over_weight_price,ceil(bcdiv($_over_weight,$v['step'],1))*$v['price'],2);

            }
        }

        #获取超出重量和超出重量金额 end#

        #获取溢价金额 start#
        $extraPriceModel = new ExtraPrice();
        $extraPrice = $extraPriceModel->where(['type'=>$type])->find();

        $extra_price = empty($extraPrice['money'])?0:$extraPrice['money'];
        $extra_node = empty($extraPrice['note'])?0:$extraPrice['note'];
        #获取溢价金额 end#


        $return_data = [
            'distance'=>$distance,
            'general_price'=>$general_price,
            'over_distance'=>$over_distance,
            'over_distance_price'=>$over_distance_price,
            'over_weight'=>$over_weight,
            'over_weight_price'=>$over_weight_price,
            'extra_price'=>$extra_price,
            'extra_node'=>$extra_node
        ];

        #获取用户折扣价格 start#
        $userLevelModel = new UserLevel();
        $userLevel = $userLevelModel
            ->field("user_level.level_id,level.value")
            ->alias("user_level")
            ->join("paotui_level level","user_level.level_id = level.id")
            ->where(['user_level.user_id'=>$user_id])->find();
        if(!empty($userLevel['level_id'])) {
            if($userLevel['value'] != 0) {//value 为0不打折
                $discount_price = bcmul($general_price,bcdiv($userLevel['value'],100,2),2);
                $discount_price = bcadd($discount_price,$over_distance_price,2);
                $discount_price = bcadd($discount_price,$over_weight_price,2);
            }

            if(isset($discount_price)){
                $return_data['discount_price'] = $discount_price;
            }
        }
        #获取用户折扣价格 end#

        return $return_data;
    }

    /**
     * 获取快递员的快递列表
     * @return array
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getPosterPostList($status,$where,$page,$limit,$field='*',$lng="",$lat="",$poster_id){
        
        
        if($status == 1){   //抢单广场
            unset($where['poster_id']);
			$yiqu=Db::name('partition_code')->where('status',1)->where('take_user_id is not null and poster_id is null')->column('paotui_post_id');
			if($yiqu){
				$yqids=array_unique($yiqu);
				// $where['id']=['in',$yqids];
			}else{
				// $where['id']=0;
			}
			// p($yqids);
			// p($where);
        }
        $work = Db::name('paotui_poster')->where(['id'=>$poster_id])->find();
		$agentId=$work['agent_id'];
		
		$wherery=[];
		if($agentId){
			$myry=Db::name('user')->where('parent_user_id|id',$agentId)->column('id');
			$myry2=Db::name('user')->where('parent_user_id|id','in',$myry)->column('id');
		// p($myry2);
		    if($status==1){
		        
			    $wherery['user_id'] = ['in',$myry2];
		    }
		}
        $where['school'] = $work['school'];
        if($status == 2){
            $where['type'] = ['neq',2];
        }
        
        $total = self::getPoseterStatusModel($status,$poster_id)->where($where)->count();
        
        switch ($status){
            case "1":   //抢单广场
            case "2":   //待揽收
                $field .= ",(2 * 6378.137* ASIN(SQRT(POW(SIN(PI()*({$lng}-from_lng)/360),2)+COS(PI()*{$lat}/180)* COS(from_lat * PI()/180)*POW(SIN(PI()*({$lat}-from_lat)/360),2)))) as from_distance,(2 * 6378.137* ASIN(SQRT(POW(SIN(PI()*({$lng}-to_lng)/360),2)+COS(PI()*{$lat}/180)* COS(to_lat * PI()/180)*POW(SIN(PI()*({$lat}-to_lat)/360),2)))) as to_distance";
                $order = "find_in_set(type,'2,1,3,5'),createtime desc";
                break;
            case "6":   //进行中
                $field .= ",(2 * 6378.137* ASIN(SQRT(POW(SIN(PI()*({$lng}-from_lng)/360),2)+COS(PI()*{$lat}/180)* COS(from_lat * PI()/180)*POW(SIN(PI()*({$lat}-from_lat)/360),2)))) as from_distance,(2 * 6378.137* ASIN(SQRT(POW(SIN(PI()*({$lng}-to_lng)/360),2)+COS(PI()*{$lat}/180)* COS(to_lat * PI()/180)*POW(SIN(PI()*({$lat}-to_lat)/360),2)))) as to_distance";
                $order = "find_in_set(type,'2,1,3,5'),createtime desc";
                break;
            case "3":   //已揽收
            case "4":   //派送中
            case "7":   //运输中（3,4）
                $field .= ",(2 * 6378.137* ASIN(SQRT(POW(SIN(PI()*({$lng}-to_lng)/360),2)+COS(PI()*{$lat}/180)* COS(to_lat * PI()/180)*POW(SIN(PI()*({$lat}-to_lat)/360),2)))) as to_distance";
                $order = "find_in_set(type,'2,1,3,5'),to_distance asc";
                break;
            default:    //其他
                $order = "createtime desc";
                break;
        }
        //设置排序
        if($lng == "" || $lat == ""){
            $field = "*";
            // $order = "status asc,createtime desc";
            //设置创建时间为排序
            $order = "createtime desc";
        }
        
        if($page){
            $data = collection(self::getPoseterStatusModel($status,$poster_id)->where($where)->where($wherery)->page($page,$limit)->field($field)->orderRaw($order)->select())->toArray();
        }else{
            $data = collection(self::getPoseterStatusModel($status,$poster_id)->where($where)->where($wherery)->field($field)->orderRaw($order)->select())->toArray();
        }
        if($status == 6){
            $newdat = [];
            foreach($data as $dak=>$dav){
                if($dav['type']!=2){
                    $newdat[] = $dav;
                }
            }
            $data = $newdat;
        }
        
        $dids = '';
        if($data){
            foreach($data as $dkk=>$dvv){
                if($dids){
                    $dids .=','. $dvv['id'];
                }else{
                    $dids = $dvv['id'];
                }
            }
        }
        
        if($status == 2||$status == 6){
            if($status == 6){
                
                $only = Db::name('paotui_only')->where(['poster_id'=>$poster_id,'status'=>['in','0,1']])->page($page,$limit)->order('createtime desc')->select();
            }else{
                $only = Db::name('paotui_only')->where(['poster_id'=>$poster_id,'status'=>0])->page($page,$limit)->order('createtime desc')->select();
                
            }
           
            $data2 = [];
            foreach($only as $ok=>$ov){
                $dt = Db::name('paotui_post')->where(['id'=>['not in',$dids]])->field($field)->where(['id'=>$ov['post_id']])->where(['status'=>['gt',-1]])->find();
                 
                if($dt){
                    $dt['status'] =3;
                    $dt['partition_code_id'] =$ov['partition_code_id'];
                    $data2[] = $dt;
                }
            }
            
            if(!$data){
                $data = $data2;
            }else{
                
                
                
                $mergedArray = array_merge($data2, $data);
               
                
                // 根据时间戳对数组排序
                usort($mergedArray, function($a, $b) {
                    return $a['timestamp'] - $b['timestamp'];
                });
                
                $data = $mergedArray;
                
            }
            
        }
        if($status == 7){
            
            $only = Db::name('paotui_only')->where(['poster_id'=>$poster_id,'status'=>1])->page($page,$limit)->order('createtime desc')->select();
            
                $data2 = [];
                foreach($only as $ok=>$ov){
                    $dt = Db::name('paotui_post')->where(['id'=>['not in',$dids]])->field($field)->where(['id'=>$ov['post_id']])->where(['status'=>['gt',-1]])->find();
                    if($dt){
                        $dt['status'] =4;
                        $dt['partition_code_id'] =$ov['partition_code_id'];
                        $data2[] = $dt;
                    }
                }
            if(!$data){
                $data = $data2;
            }else{
                $mergedArray = array_merge($data2, $data);
 
                // 根据时间戳对数组排序
                usort($mergedArray, function($a, $b) {
                    return $a['timestamp'] - $b['timestamp'];
                });
                
                $data = $mergedArray;
            }
        }
        if($status == 5){
            $only = Db::name('paotui_only')->where(['id'=>['not in',$dids]])->where(['poster_id'=>$poster_id,'status'=>2])->group('post_id')->page($page,$limit)->order('createtime desc')->select();
                $data2 = [];
                foreach($only as $ok=>$ov){
                    $dt = Db::name('paotui_post')->field($field)->where(['id'=>$ov['post_id']])->find();
            // p($dt);
                    if($dt){
                        $dt['status'] =5;
                        $dt['partition_code_id'] =$ov['partition_code_id'];
                        $data2[] = $dt;
                    }
                }
            
            if(!$data){
                $data = $data2;
            }else{
                $mergedArray = array_merge($data2, $data);
 
                // 根据时间戳对数组排序
                usort($mergedArray, function($a, $b) {
                    return $a['timestamp'] - $b['timestamp'];
                });
                
                $data = $mergedArray;
            }
        }
        if($status == 8){
            $status = 5;
            $startOfDay = strtotime(date('Y-m-d 00:00:00'));
            $where['completetime']=['gt',$startOfDay];
            $data = collection(self::getPoseterStatusModel($status,$poster_id)->where($where)->where($wherery)->field($field)->orderRaw($order)->select())->toArray();
            $only = Db::name('paotui_only')->where(['id'=>['not in',$dids]])->where(['poster_id'=>$poster_id,'status'=>2,'completetime'=>['gt',$startOfDay]])->group('post_id')->page($page,$limit)->order('completetime desc')->select();
                $data2 = [];
                foreach($only as $ok=>$ov){
                    $dt = Db::name('paotui_post')->field($field)->where(['id'=>$ov['post_id']])->find();
            // p($dt);
                    if($dt){
                        $dt['status'] =5;
                        $dt['partition_code_id'] =$ov['partition_code_id'];
                        $data2[] = $dt;
                    }
                }
            
            if(!$data){
                $data = $data2;
            }else{
                $mergedArray = array_merge($data2, $data);
 
                // 根据时间戳对数组排序
                usort($mergedArray, function($a, $b) {
                    return $a['timestamp'] - $b['timestamp'];
                });
                
                $data = $mergedArray;
            }
        }
        // p(Db::name('ppaotui_post')->getLastSql());die;
		
		$nowdate=date('Y-m-d');
        foreach ($data as &$v){
            if(!empty($v['from_distance'])){
                $v['from_distance'] = sprintf("%.1f",$v['from_distance']);
            }
            if(!empty($v['to_distance'])){
                $v['to_distance'] =  sprintf("%.1f",$v['to_distance']);
            }

            if($v['appoints_day']){
                $today = date("m-d");
                if($today == $v['appoints_day']){
                    $v['appoints_day'] = "今天";
                }

                $tomorrow = date("m-d",strtotime("+1 day",time()));
                if($tomorrow == $v['appoints_day']){
                    $v['appoints_day'] = "明天";
                }
            }
            
            if($v['type'] == 2){
                //设置brokerage
                $allcode = Db::name('partition_code')->where(['paotui_post_id'=>$v['id'],'canceltime'=>0,'status'=>1])->count();
                $price = $allcode*$work['brokerage_scale'];
                // p($work);die;
                if($work['poster_type'] == 1){
                    $v['brokerage'] = number_format($price+$v['valuable']*($work['valuable_scale']/100)+ $v['upstairs']*($work['upstairs_scale']/100),2);
                }
                
                //时间等接口
                 $station = Db::name('station')->where(['id'=>$v['from_address_id']])->where('deletetime is null')->find();
                $school = Db::name('school')->where(['id'=>$station['school']])->find();
                $v['from_district'] = $school['name'];
                $v['from_poi'] = $station['name'];
                $v['from_address'] = $station['address'];
                $v['from_name'] = $station['name'];
                $v['from_mobile'] = '';
                
                //收件 用户
                $userschool = Db::name('user_school')->field('a.*,u.vipend')
					->alias('a')->join('user u','u.id=a.user_id','left')
					->where(['a.id'=>$v['to_address_id']])->find();
                $building = Db::name('building')->where(['id'=>$userschool['building_id']])->find();
                $v['to_district'] = $school['name'];
                $v['to_poi'] = $building['name'];
                $v['to_address'] = $userschool['house_number'];
                $v['to_name'] = $userschool['nickname'];
                $v['to_mobile'] = $userschool['phone'];
				$v['isvip']=$userschool['vipend'] && $userschool['vipend']>$nowdate?1:0;
                
                //取件码
				$wqjm=['paotui_post_id'=>$v['id']];
				if($status!=1){
					// if($status==2){
						// $codes  = Db::name('partition_code')->where($wqjm)->where('take_user_id is not null')->select();
					// }else{
						// $wqjm['poster_id']=$this->auth->id;
						// $codes  = Db::name('partition_code')->where($wqjm)->select();
					// }
				    // $codes = Db::name('partition_code')->where($wqjm)->where(['id'=>['in',$v['partition_code_id']]])->select();
					$codes  = Db::name('partition_code')->where($wqjm)->select();//take_user_id is null and 
					
					//剩余
					$codes_shengyu  = Db::name('partition_code')->where($wqjm)->where('poster_id is null')->select();
					
					$zhanshi_code =  Db::name('partition_code')->where($wqjm)->where(['id'=>['in',$v['partition_code_id']],'poster_id'=>$poster_id])->select();
				   
					
					//剩余
					// echo Db::name('partition_code')->getLastSql();
				}else{
					$codes  = Db::name('partition_code')->where($wqjm)->select();//take_user_id is null and 
					//剩余
					$codes_shengyu  = Db::name('partition_code')->where($wqjm)->where('poster_id is null')->select();
					$zhanshi_code = $codes_shengyu;
				}
				
                $codearr = [];
                $yc = 0;
                foreach($zhanshi_code as $kk=>$vv){
                    if($vv['status'] == 2){
                        $yc = $yc+1;
                    }
                    //取件码分组
                    $partition = Db::name('partition')->where(['id'=>$vv['partition_id']])->find();
                    $station = Db::name('station')->where(['id'=>$partition['station_id']])->find();
                    //整理取件码
                    if($vv['partition_id'] == 0){
                        $data2 = [
                            'partition_name'=>'其他',
                            'code'=>$vv['codes'],
                            'error_type'=>$vv['error_type']
                        ];
                        $codearr[0]['data'][] =  $data2;
                        $codearr[0]['name'] = '其他';
                    }else{
                        $data2 = [
                            'partition_name'=>$partition['name'],
                            'code'=>$vv['codes'],
                            'error_type'=>$vv['error_type']
                        ];
                        $codearr[$station['id']]['data'][] =  $data2;
                        $codearr[$station['id']]['name'] = $station['name'];
                    }
                }
                $v['codearr'] = $codearr;
                $yq = count($codes)-$yc-count($codes_shengyu);
                $v['nummsg'] = '共'.count($codes).'件，已取'.$yq.'件，异常'.$yc.'件';
                
            }
            if($v['type'] == 4){
                 //收件 用户
                $userschool = Db::name('user_school')->field('a.*,u.vipend')
					->alias('a')->join('user u','u.id=a.user_id','left')
					->where(['a.id'=>$v['from_address_id']])->find();
                $building = Db::name('building')->where(['id'=>$userschool['building_id']])->find();
                $school = Db::name('school')->where(['id'=>$userschool['school_id']])->find();
                $v['from_district'] = $school['name'];
                $v['from_poi'] = $building['name'];
                $v['from_address'] = $userschool['house_number'];
                $v['from_name'] = $userschool['nickname'];
                $v['from_mobile'] = $userschool['phone'];
				$v['isvip']=$userschool['vipend'] && $userschool['vipend']>$nowdate?1:0;
            }
            if($v['type'] == 5){
                 //收件 用户
                $userschool = Db::name('user_school')->field('a.*,u.vipend')
					->alias('a')->join('user u','u.id=a.user_id','left')
					->where(['a.id'=>$v['to_address_id']])->find();
                $building = Db::name('building')->where(['id'=>$userschool['building_id']])->find();
                $school = Db::name('school')->where(['id'=>$userschool['school_id']])->find();
                $v['from_district'] = $school['name'];
                $v['from_poi'] = $building['name'];
                $v['from_address'] = $userschool['house_number'];
                $v['from_name'] = $userschool['nickname'];
                $v['from_mobile'] = $userschool['phone'];
				$v['isvip']=$userschool['vipend'] && $userschool['vipend']>$nowdate?1:0;
            }
            if($v['shopro_order_id']){
                
                $v['goods'] = Db::name('shopro_order_item')->where(['order_id'=>$v['shopro_order_id']])->select();
                $allcate = [];
                foreach($v['goods'] as $kk=>$vv){
                    $good = Db::name('shopro_goods')->where('id',$vv['goods_id'])->find();
                    $cate = Db::name('shopro_category')->where('id',$good['category_ids'])->find();
                    
                    //判断这个cate是否存在时间和起送价之类的
                    if($cate){
                        
                        if(!$cate['shop_opentime']){
                            //查看有没有maincate
                            $pcate = Db::name('shopro_category')->where('id',$cate['parent_id'])->find();
                            if($pcate['shop_opentime']){
                                $allcate[$pcate['id']]['cateinfo'] = $pcate;
                                $allcate[$pcate['id']]['goods'][] = $vv;
                            }else{
                                $allcate[$cate['id']]['cateinfo'] = $cate;
                            $allcate[$cate['id']]['goods'][] = $vv;
                            }
                        }else{
                            $allcate[$cate['id']]['cateinfo'] = $cate;
                            $allcate[$cate['id']]['goods'][] = $vv;
                        }
                    }else{
                        $allcate[0]['cateinfo'] = '无分类';
                        $allcate[0]['goods'][] = $vv;
                    }
                    
                }
                $v['allcate'] = $allcate;
                $order = Db::name('shopro_order')->where(['id'=>$v['shopro_order_id']])->find();
                $v['remark'] = $order['remark'];
            }
        }
        
        
        return array('data'=>$data,'total'=>$total);
    }

    /**
     * 按条件获取model
     * 1待抢单 2待揽收 3运输中 4派送中 5已完成 6服务中（2,3,4） -1已取消
     * @param $status
     * @return Post
     */
    private function getPoseterStatusModel($status,$poster_id){
        $model = new \app\admin\model\paotui\Post();

        switch ($status){
            case "1":   //抢单广场
                $model = $model::where(function ($query) use($status,$poster_id){
                    return $query->where(['status'=>2])->whereOr(function ($query) use ($poster_id){
                        return $query->where(['status'=>['in',[8,9]],'poster_id'=>$poster_id]);
                    });
                });
                break;
            case "2":   //待揽收
                $model = $model::where(["status"=>3]);
                break;
            case "3":   //运输中
                $model = $model::where(["status"=>4]);
                break;
            case "5":   //已送达
                $model = $model::where(["status"=>5]);
                break;
            case "6":   //服务中（2,3,4）
                $model = $model::where(["status"=>['in','3,4']]);
                break;
            case "7":   //运输中（3,4）
                $model = $model::where(["status"=>['in','4']]);
                break;
            case "-1":   //已取消
                $model = $model::where(["status"=>-1]);
                break;
            default:     //无条件
                $model = $model::where(["status"=>0]);
                break;
        }

        return $model;
    }

    /**
     * 用户获取订单详情
     */
    public function getInfoByMarket($order_no){
        $postModel = new \app\admin\model\paotui\Post();
        $postInfo = $postModel->where(['order_no'=>$order_no])->find();
        if(empty($postInfo)){
            $this->error = "订单不存在";
            return false;
        }

        /**
         * 物流轨迹
         */
        $order = [];
        $postOrderModel = new PostOrder();
        $orderList = $postOrderModel
            ->field("type,createtime")
            ->where("post_id",$postInfo['id'])
            ->order("id asc")
            ->select();
        if($orderList){
            foreach($orderList as $k=>$v){
                if($postInfo['type'] == 4){
                    $order[$k]['type_name'] = \addons\paotui\service\Post::$post_order_type2[$v['type']];
                }else{
                    $order[$k]['type_name'] = \addons\paotui\service\Post::$post_order_type[$v['type']];
                }
                $order[$k]['createtime'] = date("m-d H:i",$v['createtime']);
            }
        }

        $postInfo['order'] = $order;

        return $postInfo;
    }

    /**
     * 用户获取订单详情
     */
    public function getInfoByUser($order_no,$user_id){
        $postModel = new \app\admin\model\paotui\Post();
        $postInfo = $postModel->where(['order_no'=>$order_no,'user_id'=>$user_id])->find();
        if(empty($postInfo)){
            $this->error = "订单不存在";
            return false;
        }
        if($postInfo['poster_id']){
            $posterModel = new \app\admin\model\paotui\Poster();
            $posterInfo = $posterModel->field("id,poster_name,mobile")->where(['id'=>['in',$postInfo['poster_id']]])->select();
            
            if($posterInfo){
                $postarr = [];
                
                foreach($posterInfo as $pk=>$pv){
                    $posterService = new Poster();
                    $pv['service_num'] = $posterService->getServiceNum($pv['id']);
                    $postarr[] = $pv;
                }
                
                
                $postInfo['poster'] = $postarr;
            }
        }

        if($postInfo['appoints_day']){
            $today = date("m-d");
            if($today == $postInfo['appoints_day']){
                $postInfo['appoints_day'] = "今天";
            }

            $tomorrow = date("m-d",strtotime("+1 day",time()));
            if($tomorrow == $postInfo['appoints_day']){
                $postInfo['appoints_day'] = "明天";
            }
        }



        /**
         * 物流轨迹
         */
        $order = [];
        $postOrderModel = new PostOrder();
        $orderList = $postOrderModel
            ->field("type,createtime")
            ->where("post_id",$postInfo['id'])
            ->order("id asc")
            ->select();
           
        if($orderList){
            foreach($orderList as $k=>$v){
                 if($postInfo['type'] == 4){
                    $order[$k]['type_name'] = \addons\paotui\service\Post::$post_order_type2[$v['type']];
                }else{
                    $order[$k]['type_name'] = \addons\paotui\service\Post::$post_order_type[$v['type']];
                }
                // $order[$k]['type_name'] = \addons\paotui\service\Post::$post_order_type[$v['type']];
                $order[$k]['createtime'] = date("m-d H:i",$v['createtime']);
            }
        }

        $postInfo['order'] = $order;

        return $postInfo;
    }

    /**
     * 快递员获取订单详情
     */
    public function getInfoByPoster($order_no,$poster_id){
        $postModel = new \app\admin\model\paotui\Post();
        $postInfo = $postModel->where(['order_no'=>$order_no])->find();
        if($postInfo['type'] != 2){
            $postInfo = $postModel->where(['order_no'=>$order_no,'poster_id'=>$poster_id])->find();
            if(empty($postInfo)){
                $this->error = "订单不存在";
                return false;
            }
        }
        if($postInfo['appoints_day']){
            $today = date("m-d");
            if($today == $postInfo['appoints_day']){
                $postInfo['appoints_day'] = "今天";
            }

            $tomorrow = date("m-d",strtotime("+1 day",time()));
            if($tomorrow == $postInfo['appoints_day']){
                $postInfo['appoints_day'] = "明天";
            }
        }
        if($postInfo['type'] == 2){
            $price = $postInfo['total_price'] - $postInfo['valuable'] - $postInfo['upstairs'];
            $work = Db::name('paotui_poster')->where(['id'=>$poster_id])->find();
            if($work['poster_type'] == 1){
                if($postInfo['brokerage'] == 0){
                    $allcode = Db::name('partition_code')->where(['paotui_post_id'=>$postInfo['id'],'canceltime'=>0,'status'=>1])->count();
                    $price = $allcode*$work['brokerage_scale'];
                    $postInfo['brokerage'] = number_format($price+$postInfo['valuable']*($work['valuable_scale']/100)+ $postInfo['upstairs']*($work['upstairs_scale']/100),2);
                }
            }
            //时间等接口
            $station = Db::name('station')->where(['id'=>$postInfo['from_address_id']])->where('deletetime is null')->find();
            $school = Db::name('school')->where(['id'=>$station['school']])->find();
            $postInfo['from_district'] = $school['name'];
            $postInfo['from_poi'] = $station['name'];
            $postInfo['from_address'] = $station['address'];
            $postInfo['from_name'] = $station['name'];
            $postInfo['from_mobile'] = '';
            
            //收件 用户
            $userschool = Db::name('user_school')->where(['id'=>$postInfo['to_address_id']])->find();
            $building = Db::name('building')->where(['id'=>$userschool['building_id']])->find();
            $postInfo['to_district'] = $school['name'];
            $postInfo['to_poi'] = $building['name'];
            $postInfo['to_address'] = $userschool['house_number'];
            $postInfo['to_name'] = $userschool['nickname'];
            $postInfo['to_mobile'] = $userschool['phone'];
            
            //取件码
            $codes  = Db::name('partition_code')->where(['paotui_post_id'=>$postInfo['id'],'poster_id'=>$poster_id])->select();
            $codearr = [];
            foreach($codes as $kk=>$vv){
                //取件码分组
                $partition = Db::name('partition')->where(['id'=>$vv['partition_id']])->find();
                $station = Db::name('station')->where(['id'=>$partition['station_id']])->find();
                //整理取件码
                if($vv['partition_id'] == 0){
                    $data2 = [
                        'partition_name'=>'其他',
                        'code'=>$vv['codes'],
                    ];
                    $codearr[0]['data'][] =  $data2;
                    $codearr[0]['name'] = '其他';
                }else{
                    $data2 = [
                        'partition_name'=>$partition['name'],
                        'code'=>$vv['codes'],
                    ];
                    $codearr[$station['id']]['data'][] =  $data2;
                    $codearr[$station['id']]['name'] = $station['name'];
                }
            }
            $postInfo['codearr'] = $codearr;
            
            $codesuccess  = Db::name('partition_code')->where(['paotui_post_id'=>$postInfo['id'],'poster_id'=>$poster_id,'status'=>['in','1,2']])->select();
            foreach($codesuccess as $ck=>&$cv){
                $userposter = Db::name('paotui_poster')->where(['id'=>$cv['take_user_id']])->find();
                $cv['postername'] = $userposter['poster_name'];
                $cv['taketime'] = date('Y-m-d h:i:s',$cv['taketime']);
            }
            
            $only = Db::name('paotui_only')->where(['post_id'=>$postInfo['id']])->order('status asc')->find();
            if($only['status'] == 0){
                $postInfo['status'] = 3;
            }
            if($only['status'] == 1){
                $postInfo['status'] = 4;
            }
            if($only['status'] == 2){
                $postInfo['status'] = 5;
            }
            $postInfo['codesuccess'] = $codesuccess;
            
        }
        if($postInfo['type'] == 4){
             //收件 用户
                $userschool = Db::name('user_school')->where(['id'=>$postInfo['from_address_id']])->find();
                $building = Db::name('building')->where(['id'=>$userschool['building_id']])->find();
                $school = Db::name('school')->where(['id'=>$userschool['school_id']])->find();
                $postInfo['from_district'] = $school['name'];
                $postInfo['from_poi'] = $building['name'];
                $postInfo['from_address'] = $userschool['house_number'];
                $postInfo['from_name'] = $userschool['nickname'];
                $postInfo['from_mobile'] = $userschool['phone'];
        }
        if($postInfo['type'] == 5){
             //收件 用户
                $userschool = Db::name('user_school')->where(['id'=>$postInfo['to_address_id']])->find();
                $building = Db::name('building')->where(['id'=>$userschool['building_id']])->find();
                $school = Db::name('school')->where(['id'=>$userschool['school_id']])->find();
                $postInfo['from_district'] = $school['name'];
                $postInfo['from_poi'] = $building['name'];
                $postInfo['from_address'] = $userschool['house_number'];
                $postInfo['from_name'] = $userschool['nickname'];
                $postInfo['from_mobile'] = $userschool['phone'];
        }
        if($postInfo['shopro_order_id']){
            $postInfo['goods'] = Db::name('shopro_order_item')->where(['order_id'=>$postInfo['shopro_order_id']])->select();
            $order = Db::name('shopro_order')->where(['id'=>$postInfo['shopro_order_id']])->find();
            $postInfo['remark'] = $order['remark'];
        }
        
        
        return $postInfo;
    }

    /**
     * 拒单
     * @param $post_id
     * @param $poster_id
     * @return bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public static function refusePost($post_id,$poster_id){
        $dispatchModel = new PostDispatch();
        $dispatchInfo = $dispatchModel->where(['post_id'=>$post_id,'poster_id'=>$poster_id,'status'=>0])->find();
        if($dispatchInfo){
           if($dispatchInfo->save(['status'=>-1])){
                $postModel = new \app\admin\model\paotui\Post();
                $postInfo = $postModel->where(['id'=>$post_id,'status'=>['in','8,9']])->find();
                if($postInfo){
                    $postInfo->save(['status'=>2,'poster_id'=>0]);
                }
               return true;
           }
        }else{
            return false;
        }
    }

    /**
     * 派单接单
     * @param $post_id
     * @param $poster_id
     * @return bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public static function acceptPost($post_id,$poster){

        $dispatchModel = new PostDispatch();
        $dispatchInfo = $dispatchModel->where(['post_id'=>$post_id,'poster_id'=>$poster['id'],'status'=>0])->find();
        if($dispatchInfo){
            Db::startTrans();
            $postModel = new \app\admin\model\paotui\Post();
            $postInfo = $postModel->where(['id'=>$post_id])->find();

            if(empty($postInfo)){
                return false;
            }

            if($dispatchInfo->save(['status'=>1])){
                if($postInfo->save(['poster_id'=>$poster['id'],'status'=>3])){
                    self::addOrder(2,$postInfo['id'],$poster['id'],$poster['poster_name'],$poster['mobile']);

                    $sendTemplate = new SendTemplate();
                    $sendTemplate->create_receive_post($postInfo);

                    //提交事务
                    Db::commit();
                    return true;
                }else{
                    Db::rollback();

                    return false;
                }
            }
        }else{
            return false;
        }

    }

    /**
     * 抢单操作
     * @param $order_no
     * @return bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function beatPost($order_no,$poster,$codeclick){
        //开始事务
        
        Db::startTrans();
        $postModel = new \app\admin\model\paotui\Post();
        
        $postInfo =$postModel->where(['order_no'=>$order_no,'status'=>2])->find();
        if($postInfo['type'] != 2){
            $postInfo = $postModel->where(['poster_id'=>0,'status'=>2,'order_no'=>$order_no])->lock(true)->find();
            if(empty($postInfo)){
                $this->error = "订单已被抢";
                return false;
            }
            $sstatus = $postInfo->save(['poster_id'=>$poster['id'],'status'=>3]);
        }else{
            if(!$codeclick){
                $this->error = "请先选择取件码";
                return false;
            }
            $postid = $poster['id'];
            if($postInfo['poster_id']!=0){
                if($poster['id'] != $postInfo['poster_id']){
                    $postid = $postInfo['poster_id'].','.$poster['id'];
                }
            }
            
            if(empty($postInfo)){
                $this->error = "订单已被抢";
                return false;
            }
            $sstatus = $postInfo->save(['poster_id'=>$postid,'status'=>2,'updatetime'=>time()]);
            
            $only = [
                'poster_id'=>$poster['id'],
                'post_id'=>$postInfo['id'],
                'partition_code_id'=>$codeclick,
                'status'=>0,
                'createtime'=>time(),
                'updatetime'=>time()
                ];
            $setonly = Db::name('paotui_only')->insert($only);
           
            if(!$setonly){
                $this->error('抢单失败');
            }   
        }
        
        
        if($sstatus){
            self::addOrder(2,$postInfo['id'],$poster['id'],$poster['poster_name'],$poster['mobile']);
            if($postInfo['type'] == 2){
                $ptpost = Db::name('paotui_post')->where(['order_no'=>$order_no])->find();
                // if($ptpost['brokerage'] == 0){
                    $price = $postInfo['total_price'] - $postInfo['valuable'] - $postInfo['upstairs'];
                    $work = Db::name('paotui_poster')->where(['id'=>$poster['id']])->find();
                    if($work['poster_type'] == 1){
                        $allcode = Db::name('partition_code')->where(['paotui_post_id'=>$postInfo['id'],'canceltime'=>0,'status'=>1,'id'=>['in',$codeclick]])->count();
                        $price = $allcode*$work['brokerage_scale'];
                        $postInfo['brokerage'] = number_format($price+$postInfo['valuable']*($work['valuable_scale']/100)+ $postInfo['upstairs']*($work['upstairs_scale']/100),2);
                        //设置佣金
                        Db::name('paotui_post')->where(['order_no'=>$order_no])->update(['brokerage'=>$postInfo['brokerage'],'updatetime'=>time()]);
                    }
                    $allcode2 = Db::name('partition_code')->where(['id'=>['in',$codeclick]])->select();
                    foreach($allcode2 as $ak=>$av){
                        Db::name('partition_code')->where(['id'=>$av['id']])->update(['poster_id'=>$poster['id'],'poster_time'=>time()]);
                    }
                    //生成only订单
                   
                    $allcode3 = Db::name('partition_code')->where(['paotui_post_id'=>$postInfo['id'],'canceltime'=>0,'error_type'=>0])->where('poster_id is null')->count();
                    // p($allcode3);die;
                    if($allcode3==0){
                        $postInfo->save(['poster_id'=>$postid,'status'=>3]);
                    }
                // }
            }
            $sendTemplate = new SendTemplate();
            $sendTemplate->create_receive_post($postInfo);
            //提交事务
            Db::commit();

            return true;
        }else{
            Db::rollback();
            $this->error = "抢单失败";
            return false;
        }
    }

    /**
     * 确认取件
     * @param $order_no
     * @param $poster
     * @return bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function collectPost($order_no,$poster,$images = "",$third_code="",$trird_order_no=""){

        Db::startTrans();
        //获取当前状态
        $postModel = new \app\admin\model\paotui\Post();
        $posttype = $postModel->lock(true)->where(['order_no'=>$order_no])->find();
        if($posttype['type']  != 2){
            $postInfo = $postModel->lock(true)->where(['status'=>3,'poster_id'=>$poster['id'],'order_no'=>$order_no])->find();
            if(empty($postInfo)){
                $this->error = "订单不存在";
                Db::rollback();
                return false;
            }
			if($postInfo['appoints_day'] && $postInfo['appoints_day']!='立即取件'){
				$nowd=date('Y-m-d H:i:s',time()+60*60);
				if($postInfo['appoints_day']>$nowd){
					$this->error = "预约时间前1小时方可取件！";
					Db::rollback();
					return false;
				}
			}
    
            $data = [
                'status'=>4,
                'images'=>$images,
            ];
    
            if($postInfo->save($data)){
                self::addOrder(3,$postInfo['id'],$poster['id'],$poster['poster_name'],$poster['mobile']);
                Db::commit();
                return true;
            }
    
            $this->error = "取件失败";
            Db::rollback();
            return false;
        }else{
            $only = Db::name('paotui_only')->where(['poster_id'=>$poster['id'],'post_id'=>$posttype['id'],'status'=>0])->select();
            if(!$only){
                $this->error = "取件失败";
                return false;
            }
            foreach($only as $yk=>$yv){
                Db::name('paotui_only')->where(['id'=>$yv['id']])->update(['status'=>1,'images'=>$images]);
            }
            Db::commit();
            //判断是否需要更新主订单
            $allonly = Db::name('paotui_only')->where(['post_id'=>$posttype['id'],'status'=>['gt',0]])->select();
            $allcods = 0;
            $allimages = '';
            foreach($allonly as $k=>$v){
                $ids = explode(',',$v['partition_code_id']);
                $allcods = $allcods +count($ids);
                if($k == 0){
                    $allimages = $v['images'];
                }else{
                    $allimages .= ','.$v['images'];
                }
                
            }
            $allcds = Db::name("partition_code")->where(['paotui_post_id'=>$posttype['id'],'canceltime'=>0,'error_type'=>0])->count();
            if($allcds == $allcods){
                Db::name('paotui_post')->where(['id'=>$posttype['id']])->update(['status'=>4,'images'=>$allimages]);
            }
            Db::commit();
            
            return true;
            
        }
    }
    
    /**
     * 确认取件(衣服)
     * @param $order_no
     * @param $poster
     * @return bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function clothPost($order_no,$poster,$images = "",$clothnum,$third_code="",$trird_order_no=""){

        Db::startTrans();
        //获取当前状态
        $postModel = new \app\admin\model\paotui\Post();
        $postInfo = $postModel->lock(true)->where(['status'=>3,'poster_id'=>$poster['id'],'order_no'=>$order_no])->find();
        if(empty($postInfo)){
            $this->error = "订单不存在";
            Db::rollback();
            return false;
        }
        //判断并且扣除洗衣次数
        $user = Db::name('user')->where(['id'=>$postInfo['user_id']])->find();
        $last = $user['washnum'] - $clothnum;
        if($last>=0){
            Db::name('user')->where(['id'=>$postInfo['user_id']])->update(['washnum'=>$last]);
        }else{
            $this->error = "洗衣次数不足，请提醒顾客去商城购买洗衣次数后再下单";
            Db::rollback();
            return false;
        }
        
        
        
        
        $data = [
            'status'=>4,
            'images'=>$images,
            'cloth'=>$clothnum
        ];

        if($postInfo->save($data)){
            self::addOrder(3,$postInfo['id'],$poster['id'],$poster['poster_name'],$poster['mobile']);
            Db::commit();
            return true;
        }

        $this->error = "取件失败";
        Db::rollback();
        return false;
    }
    /**
     * 签收快递
     * @param $order_no
     * @param $poster
     * @param $lnglat
     * @param $image
     * @param $place
     * @return bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function reachPost($order_no,$poster,$lnglat,$image){
        Db::startTrans();
        $postModel = new \app\admin\model\paotui\Post();
        $post = $postModel->where(['order_no'=>$order_no])->find();
        if($post['type'] == 2){
            $getone = Db::name('paotui_only')->where(['poster_id'=>$poster['id'],'post_id'=>$post['id'],'status'=>1])->select();
            if(empty($image)){
                $this->error = "请上传照片";
                return false;
            }
            if($getone){
                foreach($getone as $ok=>$ov){
                    Db::name('paotui_only')->where(['id'=>$ov['id']])->update(['status'=>2,'reach_image'=>$image,'completetime'=>time()]);
                }
                Db::commit();
                
                //判断是否需要更新主订单
                $allonly = Db::name('paotui_only')->where(['post_id'=>$post['id'],'status'=>['gt',1]])->select();
                $allcods = 0;
                $allimages = '';
                foreach($allonly as $k=>$v){
                    $ids = explode(',',$v['partition_code_id']);
                    $allcods = $allcods +count($ids);
                    if($k == 0){
                        $allimages = $v['reach_image'];
                    }else{
                        $allimages .= ','.$v['reach_image'];
                    }
                    
                }
                $allcds = Db::name("partition_code")->where(['paotui_post_id'=>$post['id'],'canceltime'=>0,'error_type'=>0])->count();
                // p($allcds);die;
                if($allcds == $allcods){
                    Db::name('paotui_post')->where(['id'=>$post['id']])->update(['status'=>5,'reach_images'=>$allimages,'completetime'=>time()]);
                }
                Db::commit();
                
                return true;
            }else{
                $this->error="签收失败";
                return false;
            }
        }else{
            $postInfo = $postModel->lock(true)->where(['status'=>['in','3,4'],'poster_id'=>$poster['id'],'order_no'=>$order_no])->find();
            if(empty($postInfo)){
                $this->error = "快递单不存在或者当前状态不能送达";
                return false;
            }
    
            if(empty($image)){
                $this->error = "请上传照片";
                return false;
            }
    
            if($postInfo->save(['status'=>5,'reach_images'=>$image,'completetime'=>time()])){
                self::addOrder(4,$postInfo['id'],$poster['id'],$poster['poster_name'],$poster['mobile']);
    
                $sendTemplate = new SendTemplate();
                $sendTemplate->create_post_reach($postInfo);
    
                Db::commit();
                return true;
            }
    
            $this->error="签收失败";
            return false;
        }
        
    }


    /**
     *
     * @param $order_no
     * @param $transaction_id
     * @return false|void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public static function pay_success($order_no,$transaction_id){

        $postModel = new \app\admin\model\paotui\Post();
        $postInfo = $postModel->where(['order_no'=>$order_no])->find();
		// p($order_no);
        if(empty($postInfo)){
            return false;
        }
        if($postInfo['type'] == 4){
            $status = 4;
        }else{
            $status = 2;
        }
		// $type1=0;
		// $type1=$postInfo['type'];
		// p($status);die;
        if($postInfo['type'] == 2){
            if($postInfo->save(['transaction_id'=>$transaction_id,'pay_status'=>1,'paytime'=>time()])){
                $dispatch_mode = PaotuiConfig::get('dispatch_mode');
                $postIds = $postModel->where(['id'=>$postInfo['id']])->column("id");
                $data = [];
                $order_data = [];
                if($postIds){
                    foreach ($postIds as $k=>$v){
                        // $data[] =[
                            // 'post_id'=>$v,
                            // 'type'=>$dispatch_mode,
                            // 'type1'=>$type1,
                            // 'next_send_time'=>time(),
                            // 'send_num'=>0,
                            // 'send_status'=>0,
                            // 'createtime'=>time()
                        // ];
    
                        $order_data[] = [
                            'post_id'=>$v,
                            'type'=>1,
                            'createtime'=>time()
                        ];
                    }
                    // if($data){
                        // $postSocketModel = new PostSocket();
                        // $postSocketModel->insertAll($data);
                    // }
                    if($order_data){
                        $postOrderModel = new PostOrder();
                        $postOrderModel->insertAll($order_data);
                    }
					upMergeOrder(['id'=>$postInfo['id']]);
					self::createCommissionOrder($postInfo);
                }
            }
        }else{
            if($postInfo->save(['transaction_id'=>$transaction_id,'status'=>$status,'pay_status'=>1,'paytime'=>time()])){
                $dispatch_mode = PaotuiConfig::get('dispatch_mode');
                $postIds = $postModel->where(['id'=>$postInfo['id']])->column("id");
                $data = [];
                $order_data = [];
                if($postIds){
                    foreach ($postIds as $k=>$v){
                        // $data[] =[
                            // 'post_id'=>$v,
                            // 'type'=>$dispatch_mode,
                            // 'type1'=>$type1,
                            // 'next_send_time'=>time(),
                            // 'send_num'=>0,
                            // 'send_status'=>0,
                            // 'createtime'=>time()
                        // ];
    
                        $order_data[] = [
                            'post_id'=>$v,
                            'type'=>1,
                            'createtime'=>time()
                        ];
                    }
                    // if($data){
                        // $postSocketModel = new PostSocket();
                        // $postSocketModel->insertAll($data);
                    // }
                    if($order_data){
                        $postOrderModel = new PostOrder();
                        $postOrderModel->insertAll($order_data);
                    }
					upMergeOrder(['id'=>$postInfo['id']]);
					self::createCommissionOrder($postInfo);
                }
            }
        }
    }
	
    /**
     * 创建分销订单
     */
    public static function createCommissionOrder($postInfo)
    {
		$user_id=$postInfo['user_id'];
		$user=Db::name('user')->where('id',$user_id)->find();
		$agentId=$user['parent_user_id'];
		//无父级id则不写入分销订单
        if (!$agentId) {
            return false;
        }
        $commissionOrder = OrderModel::where('order_id', $postInfo['id'])->where('tb_name','paotui_post')->find();

        // 已添加过分销订单
        if ($commissionOrder) {
            return $commissionOrder;
        }
		
		/* //20240813 masks 新增扣除短信费操作 //在创建佣金时计算了
		$smsfee=config('site.paotui_sms');
		$amount=$postInfo['pay_price']-$smsfee;
		//若需其他费用再算，平台抽佣啥的用原分销逻辑，此处只加了短信费
		if($amount<=0)return;//扣除短信费小于0的不给写入了 */
		
		$comrule=db('shopro_commission_level')->where('level',1)->find();
		$cosrule=json_decode($comrule['commission_rules'],1);
		$amount=$cosrule['fee_4'];

        $commissionOrderParams = [
            'tb_name' => 'paotui_post',
            'self_buy' => 0,//非商城无自购
            'order_id' => $postInfo['id'],
            'order_item_id' => 0,
            'buyer_id' => $user_id,
            'goods_id' => 0,
            'agent_id' => $agentId,
            'amount' => $amount,
            'reward_type' => 'pay_price',
            'commission_rules' => '',
            'reward_event' => 'paid',
            'commission_order_status' => 1,  // 是否计入分销业绩
            'commission_reward_status' => RewardModel::COMMISSION_REWARD_STATUS_PENDING,  // 佣金状态
        ];

        $commissionOrder = OrderModel::create($commissionOrderParams);

        // 添加分销商推广订单业绩
		$orderAgent=Db::name('shopro_commission_agent')->where('user_id',$agentId)->find();
        if ($orderAgent['status']=='normal' && $commissionOrder->commission_order_status) {
			// 添加一级业绩  masks 自动给一级分销
			Db::name('shopro_commission_agent')->where('user_id',$agentId)->setInc('child_order_money_1', $commissionOrder->amount);
			Db::name('shopro_commission_agent')->where('user_id',$agentId)->setInc('child_order_count_1', 1);
            LogModel::add($agentId, 'order', [
                'type' => 'paid', 
                'order' => $commissionOrder,
                'item' => '',
                'buyer' => $user
            ], $user);
        }

        return $commissionOrder;
    }

    /**
     * @param $type     类型 1支付 2抢单 3取件 4送达
     * @param $post_id
     * @param $poster_id
     * @param $poster_name
     * @param $poster_mobile
     */
    public static function addOrder($type,$post_id,$poster_id,$poster_name,$poster_mobile){
        $postOrderModel = new PostOrder();
        if($postOrderModel->save([
            'type'=>$type,
            'post_id'=>$post_id,
            'poster_id'=>$poster_id,
            'poster_name'=>$poster_name,
            'poster_mobile'=>$poster_mobile
        ])){
            return true;
        }else{
            return false;
        }
    }

    /**
     * 获取快递员可以获得佣金
     * @param $brokerage
     * @param $post_type
     * @param $poster_type
     * @param $poster_brokerage_scale
     */
    public static function poster_brokerage($brokerage,$post_type,$poster_type,$brokerage_type,$poster_brokerage_scale){
        if($poster_type == 1){
            //全职无佣金
            return 0;
        }

        if($brokerage_type == 1){
            //平台默认
            $brokerageScaleModel = new Brokeragescale();
            $brokerageScaleInfo = $brokerageScaleModel->where(['type'=>$post_type])->find();
            $scale = empty($brokerageScaleInfo)?100:$brokerageScaleInfo['scale'];
        }else{
            $scale = $poster_brokerage_scale;
        }

        return bcmul($brokerage,bcdiv($scale,100,2),2);
    }

}